import traceback
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class Bases:
    def __init__(self,browser):
        self.browser = browser
        self.loctors = {
            "xpath":By.XPATH,
            "css":By.CSS_SELECTOR,
            "class name":By.CLASS_NAME,
            "id":By.ID,
            "name":By.NAME,
            "tag name":By.TAG_NAME,
            "link text":By.LINK_TEXT,
            "partial link text":By.PARTIAL_LINK_TEXT
        }

    def find_element(self,loctors,elements):
        """
        :param loctors: 传入要操作的元素方式
        :param elements: 传入具体元素内容
        :return:
        """
        try:
            ele = WebDriverWait(self.browser,10,0.5).until(EC.presence_of_element_located((self.loctors[loctors],elements)))
            return ele
        except:
            traceback.print_exc()

    def find_elements(self,loctors,elements,num):
        """
        :param loctors: 传入要操作的元素方式
        :param elements: 传入具体的元素内容
        :param num: 要操作第几个
        :return:
        """
        try:
            ele = WebDriverWait(self.browser,10,0.5).until(EC.presence_of_all_elements_located((self.loctors[loctors],elements)))[num]
            return ele
        except:
            traceback.print_exc()

    def click_element(self,loctors,elements):
        """
        :param loctors: 传入要操作的元素方式
        :param elements: 传入具体的元素内容
        :return:
        """
        self.find_element(loctors,elements).click()

    def click_elements(self,loctors,elements,num):
        self.find_elements(loctors,elements,num).click()

    def input_text(self,loctors,elements,text):
        ele = self.find_element(loctors,elements)
        #  先清空文本内容
        ele.clear()
        # 再去输入
        ele.send_keys(text)

    def input_texts(self,loctors,elements,num,text):
        """
        :param loctors: 元素方式
        :param elements: 元素
        :param num: 索引
        :param text: 输入内容
        :return:
        """
        ele = self.find_elements(loctors,elements,num)
        # 先清空
        ele.clear()
        # 再去输入
        ele.send_keys(text)

    def win_handles(self,num):
        win = self.browser.window_handles
        self.browser.switch_to.window(win[num])



